package com.shi.yibanjia.interceptors;


import com.shi.yibanjia.entity.vo.SessionAccountVO;
import com.shi.yibanjia.util.RedisUtil;
import com.shi.yibanjia.util.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.shi.yibanjia.constants.RedisConstant.DATA_TTL;
import static com.shi.yibanjia.constants.RedisConstant.LOGIN_TOKEN_KEY;
import static com.shi.yibanjia.constants.SysConstant.TOKEN_KEY;

public class CheckAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String token = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (TOKEN_KEY.equals(cookie.getName())) {
                    token = cookie.getValue();
                    break;
                }
            }
            if (token != null) {
                SessionAccountVO sessionAccountVO = RedisUtil.get(LOGIN_TOKEN_KEY +token);
                if (sessionAccountVO != null) {
                    UserContext.set(sessionAccountVO);
                    RedisUtil.set(LOGIN_TOKEN_KEY +token, sessionAccountVO, DATA_TTL);
                }
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.remove();
    }
}
